package cn.net.isir.controller.miniprogram;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.net.isir.common.*;
import cn.net.isir.entity.WxMinipUserinfo;
import cn.net.isir.service2.WxInterfaceService;
import cn.net.isir.service2.WxMinipUserinfoService;
import cn.net.isir.utils.RequestUtils;
import cn.net.isir.utils.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxubo
 * @filename WxUserController.java
 * @package cn.net.isir.controller.miniprogram
 * @email lxb@isir.net.cn
 * @date 2018/08/28
 * @comment
 * @since 1.7
 */
@RestController("minipWxUserController")
@RequestMapping(value = "/minip/wx/")
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = {Exception.class, RuntimeException.class})
public class WxUserController {

    @Resource
    private WxInterfaceService minipWxInterfaceService;
    @Resource
    private WxMinipUserinfoService wxMinipUserinfoService;

    /**
     * 获取openid和unionid
     *
     * @param obj 请求参数
     * @return 结果
     */
    @RequestMapping(method = RequestMethod.GET, value = "openid")
    public ResultObject getWxOpenid(RequestObject obj, HttpServletRequest request, HttpServletResponse response) {
        //声明返回值
        ResultObject ro;
        //声明参数解码后的储存变量
        Map<String, Object> reqParamMap = new HashMap<>();
        //需要检查的字段名
        String[] columns = new String[]{"jsCode"};
        //检查失败则返回缺失的字段提示
        if ((ro = RequestUtils.parametersCheck(obj, reqParamMap, columns)).getResult() != 200) {
            return ro;
        }
        String jsCode = String.valueOf(reqParamMap.get("jsCode"));
        Map<String, Object> resultMap = minipWxInterfaceService.getOpenid(jsCode);
        if (resultMap == null) {
            ro.setResult(500);
            ro.setMessage("请求微信公众平台获取openid失败");
            return ro;
        }
        if (!new Integer(0).equals(resultMap.get("errcode"))) {
            ro.setResult(500);
            ro.setMessage(String.valueOf(resultMap.get("errmsg")));
            ro.setObject(resultMap);
            return ro;
        }
        String openid = String.valueOf(resultMap.get("openid"));
        String session_key = String.valueOf(resultMap.get("session_key"));
        CacheManager.setOpenidSessionKey(openid, session_key);
        ro.setResult(200);
        ro.setObject(openid);
        return ro;
    }

    /**
     * 获取unionid
     *
     * @param obj 请求参数
     * @return 结果
     */
    @RequestMapping(method = RequestMethod.GET, value = "unionid")
    public ResultObject getWxUnionid(RequestObject obj, HttpServletRequest request, HttpServletResponse response) {
        //声明返回值
        ResultObject ro;
        //声明参数解码后的储存变量
        Map<String, Object> reqParamMap = new HashMap<>();
        //需要检查的字段名
        String[] columns = new String[]{"openid", "rawData", "encryptedData", "iv"};
        //检查失败则返回缺失的字段提示
        if ((ro = RequestUtils.parametersCheck(obj, reqParamMap, columns)).getResult() != 200) {
            return ro;
        }
        String openid = String.valueOf(reqParamMap.get("openid"));
        String rawData = String.valueOf(reqParamMap.get("rawData"));
        String encryptedData = String.valueOf(reqParamMap.get("encryptedData"));
        String iv = String.valueOf(reqParamMap.get("iv"));

        String session_key = CacheManager.getOpenidSessionKey(openid);
        Map<String, Object> resultMap = minipWxInterfaceService.getUnionid(encryptedData, session_key, iv);
        if (resultMap == null) {
            ro.setResult(500);
            ro.setMessage("数据解密失败，请重新打开小程序尝试。");
            return ro;
        }
        if (resultMap.get("errcode") != null) {
            if (!new Integer(0).equals(resultMap.get("errcode"))) {
                ro.setResult(500);
                ro.setMessage(String.valueOf(resultMap.get("errmsg")));
                ro.setObject(resultMap);
                return ro;
            }
        }

        /*
         * 如果没有获取到unionid，则随机一个随机字符串
         */
        Object unionidStr = resultMap.get("unionId");
        String unionid = String.valueOf(unionidStr);
        if (unionidStr == null) {
            unionid = "random-" + StringUtils.randomUUID(32 - 7);
        }

        JSONObject rawDataObj = JSON.parseObject(rawData);
        //检测是否有用户信息
        WxMinipUserinfo userInfo = new WxMinipUserinfo();
        userInfo.setOpenid(String.valueOf(openid));
        userInfo = wxMinipUserinfoService.selectOne(userInfo);
        if (userInfo == null) {
            //插入用户信息
            userInfo = new WxMinipUserinfo();
            userInfo.setOpenid(String.valueOf(resultMap.get("openId")));
//            userInfo.setUnionid(String.valueOf(resultMap.get("unionId")));
            userInfo.setUnionid(unionid);
            userInfo.setNickName(String.valueOf(resultMap.get("nickName")));
            userInfo.setAvatarUrl(String.valueOf(resultMap.get("avatarUrl")));
            userInfo.setGender(Integer.parseInt(String.valueOf(resultMap.get("gender"))));
            userInfo.setCity(String.valueOf(resultMap.get("city")));
            userInfo.setProvince(String.valueOf(resultMap.get("province")));
            userInfo.setCountry(String.valueOf(resultMap.get("country")));
            userInfo.setLanguage(String.valueOf(rawDataObj.get("language")));
            wxMinipUserinfoService.insert(userInfo);
        } else {
            userInfo.setNickName(String.valueOf(resultMap.get("nickName")));
            userInfo.setAvatarUrl(String.valueOf(resultMap.get("avatarUrl")));
            userInfo.setGender(Integer.parseInt(String.valueOf(resultMap.get("gender"))));
            userInfo.setCity(String.valueOf(resultMap.get("city")));
            userInfo.setProvince(String.valueOf(resultMap.get("province")));
            userInfo.setCountry(String.valueOf(resultMap.get("country")));
            userInfo.setLanguage(String.valueOf(rawDataObj.get("language")));
            if (unionidStr != null) {
                userInfo.setUnionid(unionid);
            } else {
                unionid = userInfo.getUnionid();
            }
            wxMinipUserinfoService.update(userInfo);
        }

        CacheManager.setUnionidSessionKey(unionid, session_key);

        //返回
        ro.setResult(200);
        ro.setObject(unionid);
        return ro;
    }

    /**
     * 微信用户信息
     *
     * @param obj 请求参数
     * @return 结果
     */
    @RequestMapping(method = RequestMethod.GET, value = "info")
    public ResultObject getWxUserInfo(RequestObject obj, HttpServletRequest request, HttpServletResponse response) {
        //声明返回值
        ResultObject ro;
        //声明参数解码后的储存变量
        Map<String, Object> reqParamMap = new HashMap<>();
        //需要检查的字段名
        String[] columns = new String[]{"unionid"};
        //检查失败则返回缺失的字段提示
        if ((ro = RequestUtils.parametersCheck(obj, reqParamMap, columns)).getResult() != 200) {
            return ro;
        }
        String client = String.valueOf(reqParamMap.get("client"));
        String unionid = String.valueOf(reqParamMap.get("unionid"));
        if ("wx".equals(client)) {
            WxMinipUserinfo userinfo = new WxMinipUserinfo();
            userinfo.setUnionid(unionid);
            userinfo = wxMinipUserinfoService.selectOne(userinfo);
            ro.setResult(200);
            ro.setMessage("success");
            ro.setObject(userinfo);
            return ro;
        }
        if ("alipay".equals(client)) {
            WxMinipUserinfo userinfo = new WxMinipUserinfo();
//            wxMinipUserinfoService.selectOne()
        }
        ro.setResult(500);
        ro.setMessage("error client");
        return ro;
    }

    public static void main(String[] args) {
//        new WxInterfaceService().getUnionid("YAJUUVHaAerz4kjH1LMshDQifFaUvQdxOPCjVbdsvxmu5lEdgLQrthWlT1CKaF+EJKlQhM4sYby7t+1RYJb//yGYWrFklpcT0IKVMyrcFCvIaOjr8NIkPOLAhHQK7Fv0ZyahmuVQLhnizAvx5euuF3meK8bRb7BVS8I3lcT0l9axz/Y3daiAYR9zP7KhA9eU0FffRoIZS8UzWyD6FXfixQ==","jU6XGD4Kqaubk83EMUxa4g==","jU6XGD4Kqaubk83EMUxa4g==");
    }
}
